package cn.kinoko.service.auth.tokenGranter;

import cn.kinoko.common.code.ErrorCodeEnum;
import cn.kinoko.common.constant.FileConstant;
import cn.kinoko.common.utils.*;
import cn.kinoko.model.auth.vo.PayloadUserVO;
import cn.kinoko.model.auth.vo.TokenAuthVO;
import cn.kinoko.model.user.dto.UserInfoDto;
import cn.kinoko.service.user.UserInfoService;
import jakarta.annotation.Resource;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author kinoko
 */
@NoArgsConstructor
@Component
@Slf4j
public class DefaultTokenGranter implements TokenGranter {

    @Resource
    private UserInfoService userInfoService;

    @Override
    public TokenAuthVO grant(Map<String, Object> params) {
        // 验证账号
        UserInfoDto user = userInfoService.getUserInfoDtoByAccount((String) params.get(GranterParams.ACCOUNT));
        ExceptionUtil.isNull(user, ErrorCodeEnum.USER_ERROR_A0224);

        // 验证密码
        String password = (String) params.get(GranterParams.PASSWORD);
        boolean match = BCrypt.checkpw(password, user.getPassword());
        ExceptionUtil.assertion(!match, ErrorCodeEnum.USER_ERROR_A0224);

        // 准备token载荷
        PayloadUserVO payload = BeanHelper.copyProperties(user, PayloadUserVO.class);
        ExceptionUtil.isNull(payload, ErrorCodeEnum.USER_ERROR_A0200);
        String token = null;
        try {
            // 读取私钥，生成token，有效期7天
            token = JwtUtils.generateTokenExpireInMinutes(payload, RSAUtil.readPrivateKey(FileConstant.PRE_KEY), 60 * 24 * 7);
        } catch (Exception e) {
            log.error("[token签发异常]:" + e.getMessage(), e);
            ExceptionUtil.throwOut(ErrorCodeEnum.USER_ERROR_A0200);
        }
        TokenAuthVO tokenAuthVO = new TokenAuthVO();
        tokenAuthVO.setToken(token);
        tokenAuthVO.setUserName(payload.getUserName());
        return tokenAuthVO;
    }


}
